package org.zoomdev.zoom.rpc.client;

import org.zoomdev.zoom.rpc.utils.RpcUtils;
import org.zoomdev.zoom.serializer.Serializer;

import java.lang.reflect.Method;

public class SimpleHandler implements Handler {

    short func;

    final ClientConnection connection;


    final Method method;
    final Serializer argumentSerializer;

    final Serializer serializer;

    final Serializer commonSerializer;


    public SimpleHandler(ClientConnection connection,
                         Method method,
                         Serializer argumentSerializer,
                         Serializer serializer,
                         Serializer commonSerializer) {
        this.connection = connection;
        this.method = method;
        this.argumentSerializer = argumentSerializer;
        this.serializer = serializer;
        this.commonSerializer = commonSerializer;
        Short id = connection.idMap.get(method.toGenericString());
        if (id != null) {
            this.func = id;
        }

    }

    public void setResult(int retFunc, byte[] ret, Completer completer) {
        if (retFunc != RpcUtils.FUNC_ERROR) {
            try{
                Object value = (ret == null || ret.length==0) ? null : serializer.deserialize(ret);
                completer.setResult(value);
            }catch (Throwable e){
                completer.setException(e);
            }

            return;
        }
        Throwable exception;
        try{
            exception = (Throwable) commonSerializer.deserialize(ret);
        }catch (Throwable e){
            exception = e;
        }
        completer.setException(exception);
    }


    @Override
    public Completer handle(Object[] args) {
        byte[] bytes = argumentSerializer.serialize(args);
        return connection.call(this, func, bytes);
    }
}
